import mongoose from "mongoose";
import { credentials } from "../config.js";
const connectionString = credentials.mongo.connectionString;

function dbInit() {
  if(!connectionString) {
    console.error("MongoDB connection string missing!");
    process.exit(1);
  }
  
  mongoose.connect(connectionString);
  const db = mongoose.connection;
  db.on("error", err => {
    console.error(`MongoDB error: ${err.message}`);
    process.exit(1);
  });
  
  db.on("open", () => console.log("MongoDB connection established!"));
  db.on("close", () => console.log("MongoDB connection terminated!"));
  return db;
}

function closeDB(db) {
  db.close(() => {
    console.log("MongoDB connection terminated!");
  });
}

export { dbInit, closeDB }